package com.shengqi.xinnongren.work.ui.home.fragments;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpFragment;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.ImageUtils;
import com.shengqi.xinnongren.common.utils.LogUtil;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.ui.Global;
import com.shengqi.xinnongren.work.ui.goods.activities.ConfirmOrderActivity2;
import com.shengqi.xinnongren.work.ui.home.activities.MainActivity;
import com.shengqi.xinnongren.work.ui.home.fragments.interfaces.OnEditStateChangeListener;
import com.shengqi.xinnongren.work.ui.home.model.CartGoodsBean;
import com.shengqi.xinnongren.work.ui.home.model.CartMoneyBean;
import com.shengqi.xinnongren.work.ui.home.presenter.HomePage4Presenter;
import com.shengqi.xinnongren.work.ui.home.view.HomePage4View;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 购物车
 */
public class HomePage4Fragment extends BaseMvpFragment<HomePage4View, HomePage4Presenter> implements HomePage4View, OnEditStateChangeListener, SwipeMenuCreator, SwipeMenuItemClickListener {

    @BindView(R.id.ll_no_goods)
    LinearLayout ll_no_goods;
    @BindView(R.id.ll_have_goods)
    LinearLayout ll_have_goods;
    @BindView(R.id.ll_have_price_difference)
    LinearLayout ll_have_price_difference;
    @BindView(R.id.ll_no_price_difference)
    LinearLayout ll_no_price_difference;
    @BindView(R.id.rv_cart)
    SwipeMenuRecyclerView mRvShoppingCart;
    @BindView(R.id.cb_select_all)
    CheckBox mCbSelectAll;
    @BindView(R.id.tv_toggle_edit_mode)
    TextView mTvToggleEditMode;
    @BindView(R.id.tv_tips)
    TextView tv_tips;
    @BindView(R.id.cb_songhuo)
    CheckBox cb_songhuo;
    @BindView(R.id.tv_total_money)
    TextView tv_total_money;
    @BindView(R.id.tv_operate)
    TextView tv_operate;

    DecimalFormat mDecimalFormat = new DecimalFormat("0.00");


    //是否为删除模式
    private boolean isDeleteMode = false;
    //被选中的商品id列表
    private HashSet<String> mGoodsSelectedIdList = new HashSet<>();
    //购物车商品列表
    private List<CartGoodsBean> mCartGoodsList = new ArrayList<>();
    private CartGoodsAdapter mCartGoodsAdapter;

    @Override
    protected int setLayoutResource() {
        return R.layout.fragment_home_page4;
    }

    @OnClick(R.id.tv_toggle_edit_mode)
    void tv_toggle_edit_mode() {
        mCartGoodsAdapter.setEditMode(!mCartGoodsAdapter.isEditMode());
    }

    @Override
    protected void lazyLoadData() {

    }

    @Override
    protected void initView() {
        mCartGoodsAdapter = new CartGoodsAdapter(mCartGoodsList, getContext());
        mCartGoodsAdapter.setOnEditStateChangeListener(this);
        mRvShoppingCart.setSwipeMenuCreator(this);
        mRvShoppingCart.setSwipeMenuItemClickListener(this);
        mRvShoppingCart.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvShoppingCart.setAdapter(mCartGoodsAdapter);

        mCbSelectAll.setOnClickListener(v -> {
            if (mCbSelectAll.isChecked())
                mCartGoodsAdapter.selectedAllItem();
            else
                mCartGoodsAdapter.resetSelectedItem();
            calculateCartGoodsMoney();
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    @Override
    protected void onVisibilityChanged(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            getData();
        }
    }

    @Override
    protected HomePage4Presenter createPresenter() {
        return new HomePage4Presenter();
    }

    /**
     * 获取购物车列表数据
     */
    private void getData() {
        if (UserManager.getInstance().isLogin()) {
            getPresenter().getCartGoodsList();
        } else {
            ll_have_goods.setVisibility(View.GONE);
            ll_no_goods.setVisibility(View.VISIBLE);
            mTvToggleEditMode.setVisibility(View.GONE);
        }
    }

    /**
     * 重置界面显示
     */
    private void resetLayoutDisplay() {
//        tv_total_money.setText("0.00");
        onEditStateChanged(false);
//        mCartGoodsAdapter.resetSelectedItem();
        ll_no_price_difference.setVisibility(View.GONE);
//        ll_have_price_difference.setVisibility(View.VISIBLE);
//        mCbSelectAll.setChecked(false);
        cb_songhuo.setChecked(false);
    }

    @OnClick({R.id.tv_coudan, R.id.tv_go_shopping})
    void couDan() {
        if (getActivity() == null)
            return;
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).checkMoudle(1);
        } else {
            startActivity(new Intent(getActivity(), MainActivity.class));
            LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(new Intent(MainActivity.BROADCAST_CHECK_CLASS));
        }
    }

    /**
     * 当购物车编辑状态发生改变时调用
     */
    @Override
    public void onEditStateChanged(boolean isEditMode) {
        mTvToggleEditMode.setText(isEditMode ? "完成" : "编辑");
        tv_operate.setText(isEditMode ? "删除" : "结算");
        isDeleteMode = isEditMode;
    }

    /**
     * 结算/删除按钮
     */
    @SuppressWarnings("all")
    @OnClick(R.id.tv_operate)
    void tv_operate() {
        String selectIdStr = getSelectedGoodsIdStr();
        if (selectIdStr.length() == 0) {
            ToastHelper.getInstance(getContext()).showWarn("请勾选商品");
            return;
        }
        LogUtil.e(String.format("%s的id: %s", isDeleteMode ? "删除" : "结算", selectIdStr));
        if (isDeleteMode) {
            getPresenter().removeCartGoods(selectIdStr);
        } else {
            ConfirmOrderActivity2.start(getContext(), selectIdStr);
        }
    }

    /**
     * 获取已选中的商品id（逗号隔开）字符串
     */
    private String getSelectedGoodsIdStr() {
        StringBuilder builder = new StringBuilder();
        for (CartGoodsBean cartGoodsBean : mCartGoodsList) {
            if (mGoodsSelectedIdList.contains(cartGoodsBean.getComId())) {
                builder.append(cartGoodsBean.getComId()).append(",");
            }
        }
        return builder.length() == 0 ? "" : builder.substring(0, builder.length() - 1);
    }


    /**
     * 删除商品成功时回调
     */
    @Override
    public void onRemoveCartGoodsSucceed() {
        getData();
    }

    /**
     * 获取购物车选中商品价格时的回调
     */
    @Override
    public void onCartMoneyCalculated(CartMoneyBean cartMoneyBean) {
        tv_total_money.setText(String.format("￥%s", mDecimalFormat.format(cartMoneyBean.getPrice())));
    }

    /**
     * 改变商品规格数量成功时的回调
     */
    @Override
    public void onSpecificationNumChanged() {
        getPresenter().getCartGoodsList();
    }

    /**
     * 获取购物车列表回调
     */
    @Override
    public void onGetCartGoodsList(List<CartGoodsBean> cartGoodsBeanList) {
        if (getActivity() != null)
            Global.notifyCartNumChanged(getActivity());
        resetLayoutDisplay();
        mCartGoodsList.clear();
        mCartGoodsList.addAll(cartGoodsBeanList);
        mCartGoodsAdapter.notifyDataSetChanged();
        updateCheckBoxCheckState();
        calculateCartGoodsMoney();
        //暂无数据
        ll_have_goods.setVisibility(mCartGoodsList.size() > 0 ? View.VISIBLE : View.GONE);
        ll_no_goods.setVisibility(mCartGoodsList.size() > 0 ? View.GONE : View.VISIBLE);
        mTvToggleEditMode.setVisibility(mCartGoodsList.size() > 0 ? View.VISIBLE : View.GONE);
    }

    /**
     * 计算购物车商品价格
     */
    private void calculateCartGoodsMoney() {
        if (isDeleteMode)
            return;
        getPresenter().calculateCartGoodsMoney(getSelectedGoodsIdStr());
    }

    /**
     * token失效回调
     */
    @Override
    public void onTokenInvalid() {
        UserManager.getInstance().clearLoginData();
        Global.reLogin(getActivity());
    }

    /**
     * 创建RecyclerView侧滑删除菜单时
     */
    @Override
    public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
        int width = (int) getResources().getDimension(R.dimen.dp_70);
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity())
                .setBackgroundColorResource(R.color.colorPrimary)
                .setText("删除")
                .setTextSize(18)
                .setTextColor(Color.WHITE)
                .setWidth(width)
                .setHeight(height);
        swipeRightMenu.addMenuItem(deleteItem);
    }

    /**
     * 点击RecyclerView侧滑删除按钮时调用
     */
    @Override
    public void onItemClick(SwipeMenuBridge menuBridge) {
        menuBridge.closeMenu();
        if (menuBridge.getDirection() == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
            getPresenter().removeCartGoods(mCartGoodsList.get(menuBridge.getAdapterPosition()).getComId());
        }
    }

    /**
     * 更新全选按钮选择状态
     */
    private void updateCheckBoxCheckState() {
        mCbSelectAll.setChecked(checkIsAllItemSelected());
    }

    /**
     * 检查是否所有商品都已选中
     */
    private boolean checkIsAllItemSelected() {
        for (CartGoodsBean cartGoodsBean : mCartGoodsList) {
            if (!mGoodsSelectedIdList.contains(cartGoodsBean.getComId()))
                return false;
        }
        return true;
    }


    public class CartGoodsAdapter extends RecyclerView.Adapter<CartGoodsAdapter.Holder> {

        private List<CartGoodsBean> mCartGoodsBeanList;
        private Context mContext;
        private boolean mIsEditMode = false;
        //编辑状态发生改变时的回调监听
        private OnEditStateChangeListener mEditStateChangeListener;

        CartGoodsAdapter(List<CartGoodsBean> cartGoodsBeanList, Context context) {
            mCartGoodsBeanList = cartGoodsBeanList;
            mContext = context;
        }


        void setOnEditStateChangeListener(OnEditStateChangeListener editStateChangeListener) {
            mEditStateChangeListener = editStateChangeListener;
        }

        boolean isEditMode() {
            return mIsEditMode;
        }

        void setEditMode(boolean editMode) {
            if (mIsEditMode == editMode)
                return;
            mIsEditMode = editMode;
            notifyDataSetChanged();
            if (mEditStateChangeListener != null)
                mEditStateChangeListener.onEditStateChanged(mIsEditMode);
        }


        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View layout = LayoutInflater.from(mContext).inflate(R.layout.item_cart_goods_layout, parent, false);
            Holder holder = new Holder(layout);
            holder.mIvMark.setOnClickListener(v -> {
                CartGoodsBean cartGoodsBean = mCartGoodsList.get(holder.getAdapterPosition());
                if (mGoodsSelectedIdList.contains(cartGoodsBean.getComId())) {
                    mGoodsSelectedIdList.remove(cartGoodsBean.getComId());
                } else {
                    mGoodsSelectedIdList.add(cartGoodsBean.getComId());
                }
                notifyDataSetChanged();
                updateCheckBoxCheckState();
                calculateCartGoodsMoney();
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {

            CartGoodsBean cartGoodsBean = mCartGoodsBeanList.get(position);

            holder.item_isNew.setVisibility(cartGoodsBean.getIsNew() == 1 ? View.VISIBLE : View.GONE);
            ImageUtils.showImage(getContext(), cartGoodsBean.getPicUrl(), holder.item_pic);
            holder.item_title.setText(cartGoodsBean.getComName());

            if (position == mCartGoodsBeanList.size() - 1) {
                holder.vLine.setVisibility(View.GONE);
            } else {
                holder.vLine.setVisibility(View.VISIBLE);
            }


            holder.setGoodsSpecList(cartGoodsBean.getSkuList());

            if (mGoodsSelectedIdList.contains(cartGoodsBean.getComId())) {
                holder.mIvMark.setImageResource(R.mipmap.ic_check_checked);
            } else {
                holder.mIvMark.setImageResource(R.mipmap.ic_check_normal);
            }
        }

        @Override
        public int getItemCount() {
            return mCartGoodsBeanList.size();
        }

        void resetSelectedItem() {
            changeAllItemSelectState(false);
        }

        void selectedAllItem() {
            changeAllItemSelectState(true);
        }


        /**
         * 改变所有item的选中状态
         */
        private void changeAllItemSelectState(boolean isCheck) {
            if (isCheck) {
                for (CartGoodsBean cartGoodsBean : mCartGoodsBeanList) {
                    mGoodsSelectedIdList.add(cartGoodsBean.getComId());
                }
            } else {
                mGoodsSelectedIdList.clear();
            }
            notifyDataSetChanged();
        }

        class Holder extends RecyclerView.ViewHolder {

            @BindView(R.id.iv_mark)
            ImageView mIvMark;
            @BindView(R.id.v_line)
            View vLine;
            @BindView(R.id.item_isNew)
            FrameLayout item_isNew;
            @BindView(R.id.item_pic)
            ImageView item_pic;
            @BindView(R.id.item_title)
            TextView item_title;

            @BindView(R.id.rv_spec)
            RecyclerView mRvSpecification;
            private ArrayList<CartGoodsBean.SkuMapBean> mSkuMap;
            private AddToCartAdapter mAdapter;

            Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                initRecyclerView();
            }

            private void initRecyclerView() {
                mSkuMap = new ArrayList<>();
                mAdapter = new AddToCartAdapter(mSkuMap);
                mRvSpecification.setAdapter(mAdapter);
                mRvSpecification.setLayoutManager(new LinearLayoutManager(getContext()));
            }

            void setGoodsSpecList(List<CartGoodsBean.SkuMapBean> skuList) {
                mSkuMap.clear();
                mSkuMap.addAll(skuList);
                mAdapter.notifyDataSetChanged();
            }
        }
    }


    public class AddToCartAdapter extends RecyclerView.Adapter<AddToCartAdapter.Holder> {
        private List<CartGoodsBean.SkuMapBean> mGoodsSpecList;

        AddToCartAdapter(List<CartGoodsBean.SkuMapBean> skuMap) {
            mGoodsSpecList = skuMap;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(LayoutInflater.from(getContext()).inflate(R.layout.item_cart_specification, parent, false));
            holder.reduce.setOnClickListener(v -> changeSpecNum(holder, mGoodsSpecList.get(holder.getAdapterPosition()), false));
            holder.plus.setOnClickListener(v -> {
                changeSpecNum(holder, mGoodsSpecList.get(holder.getAdapterPosition()), true);

                //todo 以下动画代码--------------------
//                if (getActivity() == null || getActivity().getWindow() == null) return;
//                if (!(getActivity() instanceof MainActivity)) return;
//                ImageView animationView = new ImageView(getContext());
//                ViewGroup contentViewGroup = getActivity().getWindow().getDecorView().findViewById(android.R.id.content);
//                contentViewGroup.addView(animationView);
//                ViewGroup.LayoutParams layoutParams = animationView.getLayoutParams();
//                layoutParams.width = v.getLayoutParams().width;
//                layoutParams.height = v.getLayoutParams().height;
//                animationView.setImageResource(R.drawable.ic_add_one);
//                animationView.setPadding(v.getPaddingLeft(), v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom());
//                animationView.setLayoutParams(layoutParams);
//
//                int[] shoppingCartPoint = ((MainActivity) getActivity()).getShoppingCartPosition();
//                int[] animationStartPoint = new int[2];
//                v.getLocationInWindow(animationStartPoint);
//                int startX = animationStartPoint[0];
//                int startY = animationStartPoint[1];
//                int endX = shoppingCartPoint[0] - v.getWidth() / 2;
//                int endY = shoppingCartPoint[1];
//
//                Path path = new Path();
//                path.moveTo(startX, startY);
//                path.quadTo(
//                        Math.min(startX, endX) - (Math.max(startX, endX) - Math.min(startX, endX)) / 2,
//                        Math.min(startY, endY) - (Math.max(startY, endY) - Math.min(startY, endY)) / 4,
//                        endX,
//                        endY
//                );
//
//                PathMeasure pathMeasure = new PathMeasure(path, false);
//                ValueAnimator animator = ValueAnimator.ofFloat(0, pathMeasure.getLength());
//                animator.addUpdateListener(animation -> {
//                    float position = (float) animation.getAnimatedValue();
//                    float[] point = new float[2];
//                    pathMeasure.getPosTan(position, point, null);
//                    animationView.setX(point[0]);
//                    animationView.setY(point[1]);
//                });
//                animator.addListener(new AnimatorListenerAdapter() {
//                    @Override
//                    public void onAnimationEnd(Animator animation) {
//                        ((ViewGroup) animationView.getParent()).removeView(animationView);
//                    }
//                });
//                animator.setDuration(400);
//                animator.setInterpolator(new AccelerateInterpolator());
//                animator.start();
            });
            return holder;
        }

        private void changeSpecNum(@NonNull Holder holder, CartGoodsBean.SkuMapBean bean, boolean isAdd) {
            String numStr = holder.item_num.getText().toString();
            if (numStr.trim().length() == 0) return;
            int num = Integer.parseInt(numStr);
            if (isAdd)
                ++num;
            else
                num = num <= 0 ? 0 : num - 1;
            getPresenter().changeSpecNum(bean.getSkuId(), num);
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            CartGoodsBean.SkuMapBean bean = mGoodsSpecList.get(position);
            holder.item_price.setText(String.format("￥%s", bean.getPrice()));
            holder.tv_sku_name.setText(TextUtils.isEmpty(bean.getSkuName()) ? "" :String.format("/%s", bean.getSkuName()));
            holder.item_unit_price.setText(String.format("单价：￥%s", bean.getUnitPrice()));
            holder.item_num.setText(String.valueOf(bean.getShopCarNum()));
            if (bean.getActivityType() == 1) {
                setEnable(holder, false);
            } else {
                setEnable(holder, true);
            }
        }

        private void setEnable(@NonNull Holder holder, boolean enable) {
            holder.item_num.setAlpha(enable ? 1f : .5f);
            holder.plus.setAlpha(enable ? 1f : .5f);
            holder.reduce.setAlpha(enable ? 1f : .5f);
            holder.plus.setEnabled(enable);
            holder.reduce.setEnabled(enable);
        }

        @Override
        public int getItemCount() {
            return mGoodsSpecList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_price)
            TextView item_price;
            @BindView(R.id.item_unit_price)
            TextView item_unit_price;
            @BindView(R.id.tv_sku_name)
            TextView tv_sku_name;
            @BindView(R.id.iv_plus)
            ImageView plus;
            @BindView(R.id.iv_reduce)
            ImageView reduce;
            @BindView(R.id.item_num)
            TextView item_num;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
    }

}
